﻿using Volo.Abp.Domain.Services;
using Volo.Abp.Domain.Repositories;
using Itech_Run.Sys.Domain.Entity;
using Itech_Run.Domain.Shared.Exception;
using Itech_Run.Domain.Shared.Localization.Back;
using Microsoft.Extensions.Localization;
using Itech_Run.Domain.Shared.Const;

namespace Itech_Run.Sys.Domain.Manager
{
    public class Sys_UserManager : DomainService
    {
        private readonly IRepository<Sys_User, string> _userRepository;
        private readonly IStringLocalizer<BackResource> _localizer;
        public Sys_UserManager(IRepository<Sys_User, string> userRepository, IStringLocalizer<BackResource> localizer)
        {
            _userRepository = userRepository;
            _localizer = localizer;
        }

        public async Task Check_UniqueAsync(Sys_User entity)
        {
            await Check_UniqueUserNameAsync(entity.Id, entity.UserName);
            await Check_UniqueEmailAsync(entity.Id, entity.Email);
            await Check_UniqueMobileAsync(entity.Id, entity.MobileNo);
            await Check_UniqueNicknameAsync(entity.Id, entity.Nickname);
        }

        private async Task Check_UniqueUserNameAsync(string id, string userName)
        {
            if ((await _userRepository.GetQueryableAsync()).Where(p => p.UserName == userName && p.Id != id).Any())
                throw new CustomFriendlyException(BackErrorConst.UserNameAlreadyExists, _localizer[BackErrorConst.UserNameAlreadyExists]);
        }

        private async Task Check_UniqueEmailAsync(string id, string? email)
        {
            if (!string.IsNullOrEmpty(email))
                if ((await _userRepository.GetQueryableAsync()).Where(p => p.Email == email && p.Id != id).Any())
                    throw new CustomFriendlyException(BackErrorConst.UserEmailAlreadyExists, _localizer[BackErrorConst.UserEmailAlreadyExists]);
        }

        private async Task Check_UniqueMobileAsync(string id, string? mobile)
        {
            if (!string.IsNullOrEmpty(mobile))
                if ((await _userRepository.GetQueryableAsync()).Where(p => p.MobileNo == mobile && p.Id != id).Any())
                    throw new CustomFriendlyException(BackErrorConst.UserMobileAlreadyExists, _localizer[BackErrorConst.UserMobileAlreadyExists]);
        }

        private async Task Check_UniqueNicknameAsync(string id, string? nickname)
        {
            if (!string.IsNullOrEmpty(nickname))
                if ((await _userRepository.GetQueryableAsync()).Where(p => p.Nickname == nickname && p.Id != id).Any())
                    throw new CustomFriendlyException(BackErrorConst.UserNicknameAlreadyExists, _localizer[BackErrorConst.UserNicknameAlreadyExists]);
        }
    }
}
